import Vue from 'vue'
import VueRouter from 'vue-router'
import Login from '../components/Login.vue'

Vue.use(VueRouter)

const routes = [
  {
    path: '/Home',
    name: 'Home',
    component: resolve => require(['../views/Home.vue'], resolve),
    children: [
      {
        path: '/HomePage',
        name: 'HomePage',
        component: resolve => require(['../views/HomePage/HomePage.vue'], resolve)
      },
      {
        path: '/DeviceManage',
        name: 'DeviceManage',
        component: resolve => require(['../views/DeviceManage.vue'], resolve)
      },
      {
        path: '/ElectricFence',
        name: 'ElectricFence',
        component: resolve => require(['../views/ElectricFence.vue'], resolve)
      },
      {
        path: '/SystemManage',
        name: 'SystemManage',
        component: resolve => require(['../views/SystemManage.vue'], resolve)
      },
      {
        path: '/History',
        name: 'History',
        component: resolve => require(['../views/History.vue'], resolve)
      }
    ]
  },
  {
    path: '/Login',
    name: 'Login',
    component: Login
  },
  {
    path: '/',
    redirect: '/Login'
  }
]

const router = new VueRouter({
  routes
})

// 导航守卫
// 使用 router.beforeEach 注册一个全局前置守卫，判断用户是否登陆
router.beforeEach((to, from, next) => {
  if (to.path === 'Login') { next() } else {
    const token = sessionStorage.getItem('Authorization')
    if (token === 'null' || token === '') {
      next('Login')
    } else {
      next()
    }
  }
})

export default router
